// https://zh.cppreference.com/w/cpp/thread/barrier
#include <barrier>
#include <iostream>
#include <string>
#include <syncstream>
#include <thread>
#include <vector>

int main()
{
    const auto workers = {"Anil", "Busara", "Carl"};

    auto on_completion = []() noexcept
    {
        // 此处无需锁定
        static auto phase =
            "... 完成\n"
            "清理...\n";
        std::cout << phase;
        phase = "... 完成\n";
    };

    std::barrier sync_point(std::ssize(workers), on_completion);

    auto work = [&](std::string name)
    {
        std::string product = "  " + name + " 已工作\n";
        std::osyncstream(std::cout) << product;  // OK, op<< 的调用是原子的
        sync_point.arrive_and_wait();

        product = "  " + name + " 已清理\n";
        std::osyncstream(std::cout) << product;
        sync_point.arrive_and_wait();
    };

    std::cout << "启动...\n";
    std::vector<std::jthread> threads;
    threads.reserve(std::size(workers));
    for (auto const& worker : workers)
        threads.emplace_back(work, worker);

    return 0;
}